<?php
namespace app\massage\controller;
use app\ApiRest;

use app\massage\model\Article;
use app\massage\model\CarAtvContent;
use app\massage\model\CarAtvList;
use app\massage\model\CarAtvRecord;
use app\massage\model\CarDriver;
use app\massage\model\CarGame;
use app\massage\model\CarType;
use app\massage\model\Coach;
use app\massage\model\CoachCollect;
use app\massage\model\Comment;
use app\massage\model\Goods;
use app\massage\model\Order;
use app\massage\model\Service;
use app\Rest;


use app\massage\model\Banner;

use app\massage\model\Car;
use app\massage\model\Config;

use app\massage\model\User;
use think\App;

use think\facade\Db;
use think\Request;



class Index extends ApiRest
{

    protected $model;

    protected $article_model;

    protected $coach_model;

    protected $banner_model;

    protected $car_model;

    protected $record_model;

    protected $driver_model;

    protected $atv_model;

    protected $game_model;


    public function __construct(App $app) {

        parent::__construct($app);

        $this->model = new Goods();

        $this->banner_model = new Banner();

        $this->car_model = new Car();

        $this->game_model = new CarGame();

        $this->record_model = new CarAtvRecord();

        $this->driver_model = new CarDriver();

        $this->atv_model = new CarAtvList();

        $this->atv_model->initAtv();



    }

    /**
     * @author chenniang
     * @DataTime: 2021-03-23 09:20
     * @功能说明:首页
     */
   public function index(){

       $dis = [

           'uniacid' => $this->_uniacid,

           'status'  => 1
       ];

       $data['banner']  = $this->banner_model->where($dis)->field('id,img,link')->order('top desc,id desc')->select()->toArray();
       //所有专业车手
//       $user_id = $this->driver_model->where(['status'=>2])->column('user_id');

       $where[] = ['a.have_game','=',1];

       $where[] = ['a.major','=',1];

       $where[] = ['a.type','=',2];

       $speed_record = $this->game_model->topRecordList($where,3);
       //普通组车手成绩
       $data['speed_record'] = $speed_record['data'];

       $atv_dis = [

           'uniacid'    => $this->_uniacid,
           //查询已经结束的
           'atv_status' => 3,

           'status'     => 1
       ];
       //查询最近的一个结束的活动
       $atv = $this->atv_model->where($atv_dis)->order('atv_e_time desc')->find();

       if(!empty($atv)){

           $atv = $atv->toArray();

           $i_dis = [

               'a.atv_id' => $atv['id'],

//               'a.status' => 2
           ];
            //积分排行榜
           $data['integral']['record'] = $this->record_model->integralRecordList($i_dis,4);

           $data['integral']['record'] = $data['integral']['record']['data'];
           //时间
           $data['integral']['time']   = date('Y.m.d',$atv['atv_s_time']).'-'.date('Y.m.d',$atv['atv_e_time']);

           $data['integral']['atv_id'] = $atv['id'];
       }

       $atv_diss[] = ['uniacid','=',$this->_uniacid];

       $atv_diss[] = ['status','=',1];

       $atv_diss[] = ['app_s_time','<',time()];

       $atv_diss[] = ['app_e_time','>',time()];

       $data['atv'] = $this->atv_model->where($atv_diss)->order('app_s_time')->find();

       if(!empty($data['atv'])){

           $data['atv'] = $data['atv']->toArray();

           $data['atv']['time'] = date('Y.m.d',$data['atv']['atv_s_time']).'-'.date('Y.m.d',$data['atv']['atv_e_time']);

       }

       $article_model = new Article();

       $arr = [
            //热点
           '1' => 'hot_article',
            //赛事
           '2' => 'game_article',

       ];
        //获取热点文章和赛事文章
       foreach ($arr as $k=>$value){

           $dis = [

               'type' => $k,

               'uniacid' => $this->_uniacid,

               'status' => 1
           ];

           $data[$value] = $article_model->where($dis)->order('top desc,id desc')->limit(3)->select()->toArray();

       }


       return $this->success($data);

   }



    /**
     * @author chenniang
     * @DataTime: 2021-09-16 14:31
     * @功能说明:比赛成绩排行版
     */
    public function resultTopList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.have_game','=',1];
        //1普通组 2专业组
        $dis[] = ['a.major','=',$input['type']];
        //预约的不算
        $dis[] = ['a.type','=',2];

        if(!empty($input['time'])){

            $data = $this->game_model->timeTopRecordList($dis,10,$input['time']);

        }else{

            $data = $this->game_model->topRecordList($dis,10);

        }

        return $this->success($data);
    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 14:52
     * @功能说明:所有已经完成的活动
     */
    public function successAtvList(){

        $input = $this->_param;

        $atv_dis[] = ['uniacid','=',$this->_uniacid];

        $atv_dis[] = ['status','=',1];

        if(!empty($input['title'])){

            $atv_dis[] = ['title','like','%'.$input['title'].'%'];
        }

        if(!empty($input['atv_status'])){

            $atv_dis[] = ['atv_status','=',$input['atv_status']];
        }

        $atv = $this->atv_model->where($atv_dis)->order('atv_s_time ,id desc')->paginate(10)->toArray();

        if(!empty($atv['data'])){

            foreach ($atv['data'] as &$v){

                $v['time'] = date('Y.m.d',$v['atv_s_time']).'-'.date('Y.m.d',$v['atv_e_time']);

                $v['app_status'] = 1;
                //已经开始
                if($v['app_s_time']<time()){

                    $v['app_status'] = 2;
                }
                //已经结束
                if($v['app_e_time']<time()){

                    $v['app_status'] = 3;
                }
                //剩余数量
                $v['surplus_num'] = $v['atv_num']-$v['have_num'] ;

                $v['surplus_num'] = $v['surplus_num']>0?$v['surplus_num']:0;

            }

        }

        return $this->success($atv);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-28 17:43
     * @功能说明:赛事积分排行榜
     */
    public function integralRecordList(){

        $input = $this->_param;

        $where[] = ['a.uniacid','=',$this->_uniacid];

        $where[] = ['a.atv_id','=',$input['atv_id']];
        //报名记录情况
        $data = $this->record_model->integralRecordList($where,10);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 14:55
     * @功能说明:活动详情
     */

    public function atvInfo(){

        $this->record_model->autoCancelRecord();

        $input = $this->_param;

        $dis = [

            'id' => $input['id']
        ];

        $data = $this->atv_model->dataInfo($dis);
        //活动时间
        $data['atv_time'] = date('Y.m.d H:i',$data['atv_s_time']).' - '.date('Y.m.d H:i',$data['atv_e_time']);
        //报名时间
        $data['app_time'] = date('Y.m.d H:i',$data['app_s_time']).' - '.date('Y.m.d H:i',$data['app_e_time']);

        $where[] = ['a.uniacid','=',$this->_uniacid];

        $where[] = ['a.atv_id','=',$input['id']];

        $where[] = ['a.pay_type','>',1];
        //报名记录情况
        $data['record_list'] = $this->record_model->integralRecordList($where,10);

        $re_where[] = ['atv_id','=',$input['id']];

        $re_where[] = ['user_id','=',$this->getUserId()];

        $re_where[] = ['pay_type','>',0];

        $have_app = $this->record_model->dataInfo($re_where);
        //自己是否已经报名
        $data['have_app'] = !empty($have_app)?1:0;
        //
        $content_model = new CarAtvContent();
        //报名内容
        $data['content_text'] = $content_model->where('id','in',$data['content'])->where(['status'=>1])->select()->toArray();

        $data['app_status'] = 1;
        //已经开始
        if($data['app_s_time']<time()){

            $data['app_status'] = 2;
        }
        //已经结束
        if($data['app_e_time']<time()){

            $data['app_status'] = 3;
        }

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 15:01
     * @功能说明:报名活动
     */
    public function appAtv(){

        $input = $this->_input;

        $dis = [

            'id' => $input['atv_id'],

            'status' => 1
        ];

        $atv = $this->atv_model->dataInfo($dis);

        if(empty($atv)){

            $this->errorMsg('活动已下架');
        }
        //已经报名人数
        $where[] = ['atv_id','=',$input['atv_id']];
        //去掉已经删除的
        $where[] = ['pay_type','>',0];

        $where[] = ['user_id','=',$this->getUserId()];
        //查询自己有没有报名过
        $user_num = $this->record_model->where($where)->count();

        if(!empty($user_num)){

            $this->errorMsg('你已报名或有报名订单未支付');

        }
        //防止并发做了一个简单的锁
        if($atv['have_num']>=$atv['atv_num']){

            $this->errorMsg('报名人数已满');

        }

        $car_type_model = new CarType();

        $car_type = $car_type_model->dataInfo(['id'=>$atv['car_type_id']]);

        if(empty($car_type)){

            $this->errorMsg('车型不存在');
        }
        //查询自己是否是专业车手
        $is_major = $this->driver_model->dataInfo(['user_id'=>$this->getUserId(),'status'=>2]);

        $is_major = !empty($is_major)?1:0;
        //判断车手身份
        if($is_major==1&&$car_type['major']==0){

            $this->errorMsg('只有普通车手才能报名');
        }
        //判断车手身份
        if($is_major==0&&$car_type['norm']==0){

            $this->errorMsg('只有专业车手才能报名');
        }

//        $config = new Config();
//
//        $member_config_model = new \app\member\model\Config();

       // $member_config = $member_config_model->configInfo(['uniacid'=>$this->_uniacid]);

        Db::startTrans();

        $insert = [

            'uniacid'    => $this->_uniacid,

            'user_id'    => $this->getUserId(),

            'atv_id'     => $input['atv_id'],

            'start_time' => $atv['atv_s_time'],

            'end_time'   => $atv['atv_e_time'],

            'content'    => $input['content'],

            'order_code' => orderCode(),

            'pay_price'  => $atv['pay_price'],

            'balance'    => !empty($input['is_balance'])?$atv['pay_price']:0,

            'over_time'  => time()+3600,

            'car_type_id'=> $atv['car_type_id'],

            'number'     => $atv['number'],
            //付费获得的积分
          //  'get_integral'=> empty($input['is_balance'])?floor($atv['pay_price']*$member_config['integral_cash']):0,

        ];

        $res = $this->record_model->dataAdd($insert);

        if(empty($res)){

            Db::rollback();

            $this->errorMsg('报名失败，请重试');

        }

        $res = $this->atv_model->dataUpdate(['id'=>$insert['atv_id'],'have_num'=>$atv['have_num']],['have_num'=>$atv['have_num']+1]);

        if(empty($res)){

            Db::rollback();

            $this->errorMsg('报名失败，请重试');

        }

        Db::commit();
        //0元支付
        if($insert['pay_price']<=0){

            $this->record_model->dataResult($insert['order_code'],$insert['order_code']);

            return $this->success([]);

        }

        if(!empty($insert['balance'])){

            $user_model = new User();

            $user = $user_model->dataInfo(['id'=>$insert['user_id']]);

            if($user['balance']<$insert['balance']){

                $this->errorMsg('余额不足');
            }

            $this->record_model->dataResult($insert['order_code'],$insert['order_code']);

            return $this->success([]);


        }else{
            //微信支付
            $pay_controller = new IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"carAtvApp",['type' => 'carAtvApp' , 'out_trade_no' => $insert['order_code']],$insert['pay_price']);

            $arr['pay_list']= $jsApiParameters;

//            $id = $this->record_model->getLastInsID();

            $arr['record']  = $this->record_model->dataInfo(['order_code'=>$insert['order_code']]);

            return $this->success($arr);

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-27 10:25
     * @功能说明:报名记录重新支付
     */
    public function atvRecordRePay(){

        $input = $this->_input;

        $record = $this->record_model->dataInfo(['id'=>$input['record_id']]);

        if($record['pay_type']!=1){

            $this->errorMsg('订单已经失效');
        }

        if(!empty($record['balance'])){

            $user_model = new User();

            $user = $user_model->dataInfo(['id'=>$record['user_id']]);

            if($user['balance']<$record['balance']){

                $this->errorMsg('余额不足');
            }

            $this->record_model->dataResult($record['order_code'],$record['order_code']);

            return $this->success([]);


        }else{
            //微信支付
            $pay_controller = new IndexWxPay($this->app);
            //支付
            $jsApiParameters= $pay_controller->createWeixinPay($this->payConfig(),$this->getUserInfo()['openid'],$this->_uniacid,"carAtvApp",['type' => 'carAtvApp' , 'out_trade_no' => $record['order_code']],$record['pay_price']);

            $arr['pay_list']= $jsApiParameters;

            return $this->success($arr);

        }

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 15:57
     * @功能说明:文章列表
     */
    public function articleList(){

        $input = $this->_param;

        $article_model = new Article();

        $dis = [

            'uniacid' => $this->_uniacid,

            'status' => 1
        ];

        if(!empty($input['type'])){

            $dis['type'] = $input['type'];
        }

        $data = $article_model->dataList($dis);

        return $this->success($data);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-09-16 16:02
     * @功能说明:文章详情
     */
    public function articleInfo(){

        $input = $this->_param;

        $article_model = new Article();

        $dis = [

            'id' => $input['id']
        ];

        $data = $article_model->dataInfo($dis);

        $data['create_time'] = date('Y.m.d H:i',$data['create_time']);

        $article_model->dataUpdate(['id'=>$input['id']],['iv'=>$data['iv']+1]);

        return $this->success($data);


    }





    /**
     * @author chenniang
     * @DataTime: 2021-03-23 14:16
     * @功能说明:获取配置信息
     */
   public function configInfo(){

       $dis = [

           'uniacid' => $this->_uniacid
       ];

       $config_model = new Config();

       $config = $config_model->dataInfo($dis);

       return $this->success($config);

   }






    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:07
     * @功能说明:购物车信息
     */
    public function carInfo(){

        $input = $this->_param;
        //购物车信息
        $car_info   = $this->car_model->carPriceAndCount($this->getUserId(),1);

        return $this->success($car_info);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-07-23 09:48
     * @功能说明:再来一单
     */
    public function onceMoreOrder(){

        $input = $this->_input;

        $order_model = new Order();

        $order = $order_model->dataInfo(['id'=>$input['order_id']]);

        $coach = $this->coach_model->dataInfo(['id'=>$order['coach_id']]);

        if($coach['status']!=2||$coach['is_work']==0){

            $this->errorMsg('技师未上班');
        }
        //清空购物车
        $this->car_model->where(['user_id'=>$this->getUserId(),'coach_id'=>$order['coach_id']])->delete();

        Db::startTrans();

        foreach ($order['order_goods'] as $v){

            $ser = $this->model->dataInfo(['id'=>$v['goods_id']]);

            if(empty($ser)||$ser['status']!=1){

                Db::rollback();

                $this->errorMsg('服务已经下架');
            }

            $dis = [

                'user_id'   => $this->getUserId(),

                'uniacid'   => $this->_uniacid,

                'coach_id'  => $order['coach_id'],

                'service_id'=> $v['goods_id'],

                'num'       => $v['num']
            ];

            $res = $this->car_model->dataAdd($dis);
        }

        Db::commit();

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:46
     * @功能说明:添加到购物车
     */
    public function addCar(){

        $input = $this->_input;

        $insert = [

            'uniacid'  => $this->_uniacid,

            'user_id'  => $this->getUserId(),

            'goods_id' => $input['goods_id'],

        ];

        $info = $this->car_model->dataInfo($insert);
        //增加数量
        if(!empty($info)){

            $res = $this->car_model->dataUpdate(['id'=>$info['id']],['num'=>$info['num']+$input['num']]);

        }else{
            //添加到购物车
            $insert['num'] = $input['num'];

            $insert['status'] = 1;

            $res = $this->car_model->dataAdd($insert);

            $id  = $this->car_model->getLastInsID();

            return $this->success($id);
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:54
     * @功能说明:删除购物车
     */
    public function delCar(){

        $input = $this->_input;

        $info = $this->car_model->dataInfo(['id'=>$input['id']]);
        //加少数量
        if($info['num']>$input['num']){

            $res = $this->car_model->dataUpdate(['id'=>$info['id']],['num'=>$info['num']-$input['num']]);

        }else{

            $res = $this->car_model->where(['id'=>$info['id']])->delete();
        }

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-25 10:39
     * @功能说明:
     */
    public function carUpdate(){

        $input = $this->_input;

        $res = $this->car_model->where('id','in',$input['id'])->update(['status'=>$input['status']]);

        return $this->success($res);

    }


    /**
     * @author chenniang
     * @DataTime: 2021-03-24 14:59
     * @功能说明:批量删除购物车
     */
    public function delSomeCar(){

        $input = $this->_input;

        $dis = [

            'uniacid' => $this->_uniacid,

            'user_id' => $this->getUserId(),

//            'coach_id'=> $input['coach_id'],

        ];

        $res = $this->car_model->where($dis)->delete();

        return $this->success($res);

    }



    /**
     * @author chenniang
     * @DataTime: 2021-07-05 23:16
     * @功能说明:评价列表
     */
    public function commentList(){

        $input = $this->_param;

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.status','=',1];

        if(!empty($input['coach_id'])){

            $dis[] = ['d.id','=',$input['coach_id']];
        }

        if(!empty($input['coach_name'])){

            $dis[] = ['d.coach_name','like','%'.$input['coach_name'].'%'];
        }

        if(!empty($input['goods_name'])){

            $dis[] = ['c.goods_name','like','%'.$input['goods_name'].'%'];

        }

        $comment_model = new Comment();

        $data = $comment_model->dataList($dis);

        if(!empty($data['data'])){

            foreach ($data['data'] as &$v){

                $v['create_time'] = date('Y-m-d H:i:s',$v['create_time']);

            }
        }

        return $this->success($data);

    }








}
